[[...path]].page.tsx 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666
  1. import React, { useEffect } from 'react';
  2. import EventEmitter from 'events';
  3. import {
  4. isClient, isIPageInfoForEntity, pagePathUtils, pathUtils,
  5. } from '@growi/core';
  6. import type {
  7. IDataWithMeta, IPageInfoForEntity, IPagePopulatedToShowRevision, IUser, IUserHasId,
  8. } from '@growi/core';
  9. import ExtensibleCustomError from 'extensible-custom-error';
  10. import {
  11. GetServerSideProps, GetServerSidePropsContext,
  12. } from 'next';
  13. import { serverSideTranslations } from 'next-i18next/serverSideTranslations';
  14. import dynamic from 'next/dynamic';
  15. import Head from 'next/head';
  16. import { useRouter } from 'next/router';
  17. import superjson from 'superjson';
  18. import { useCurrentGrowiLayoutFluidClassName } from '~/client/services/layout';
  19. import { Comments } from '~/components/Comments';
  20. import { MainPane } from '~/components/Layout/MainPane';
  21. import { PageAlerts } from '~/components/PageAlert/PageAlerts';
  22. // import { useTranslation } from '~/i18n';
  23. import { PageContentFooter } from '~/components/PageContentFooter';
  24. import { DrawioViewerScript } from '~/components/Script/DrawioViewerScript';
  25. import { UsersHomePageFooterProps } from '~/components/UsersHomePageFooter';
  26. import type { CrowiRequest } from '~/interfaces/crowi-request';
  27. // import { renderScriptTagByName, renderHighlightJsStyleTag } from '~/service/cdn-resources-loader';
  28. // import { useRendererSettings } from '~/stores/renderer';
  29. // import { EditorMode, useEditorMode, useIsMobile } from '~/stores/ui';
  30. import type { EditorConfig } from '~/interfaces/editor-settings';
  31. import { IPageGrantData } from '~/interfaces/page';
  32. import type { RendererConfig } from '~/interfaces/services/renderer';
  33. import type { ISidebarConfig } from '~/interfaces/sidebar-config';
  34. import type { IUserUISettings } from '~/interfaces/user-ui-settings';
  35. import type { PageModel, PageDocument } from '~/server/models/page';
  36. import type { PageRedirectModel } from '~/server/models/page-redirect';
  37. import type { UserUISettingsModel } from '~/server/models/user-ui-settings';
  38. import { useEditingMarkdown } from '~/stores/editor';
  39. import { useHasDraftOnHackmd, usePageIdOnHackmd, useRevisionIdHackmdSynced } from '~/stores/hackmd';
  40. import { useSWRxCurrentPage, useSWRxIsGrantNormalized } from '~/stores/page';
  41. import { useRedirectFrom } from '~/stores/page-redirect';
  42. import { useRemoteRevisionId } from '~/stores/remote-latest-page';
  43. import {
  44. useSelectedGrant,
  45. usePreferDrawerModeByUser, usePreferDrawerModeOnEditByUser, useSidebarCollapsed, useCurrentSidebarContents, useCurrentProductNavWidth,
  46. } from '~/stores/ui';
  47. import { useSetupGlobalSocket, useSetupGlobalSocketForPage } from '~/stores/websocket';
  48. import loggerFactory from '~/utils/logger';
  49. // import { isUserPage, isTrashPage, isSharedPage } from '~/utils/path-utils';
  50. // import GrowiSubNavigation from '../client/js/components/Navbar/GrowiSubNavigation';
  51. // import GrowiSubNavigationSwitcher from '../client/js/components/Navbar/GrowiSubNavigationSwitcher';
  52. import { DescendantsPageListModal } from '../components/DescendantsPageListModal';
  53. import { BasicLayoutWithEditorMode } from '../components/Layout/BasicLayout';
  54. import GrowiContextualSubNavigation from '../components/Navbar/GrowiContextualSubNavigation';
  55. import DisplaySwitcher from '../components/Page/DisplaySwitcher';
  56. // import { serializeUserSecurely } from '../server/models/serializers/user-serializer';
  57. // import PageStatusAlert from '../client/js/components/PageStatusAlert';
  58. import type { PageSideContentsProps } from '../components/PageSideContents';
  59. import {
  60. useCurrentUser,
  61. useIsLatestRevision,
  62. useIsForbidden, useIsNotFound, useIsSharedUser,
  63. useIsEnabledStaleNotification, useIsIdenticalPath,
  64. useIsSearchServiceConfigured, useIsSearchServiceReachable, useDisableLinkSharing,
  65. useDrawioUri, useHackmdUri, useDefaultIndentSize, useIsIndentSizeForced,
  66. useIsAclEnabled, useIsSearchPage, useTemplateTagData, useTemplateBodyData, useIsEnabledAttachTitleHeader,
  67. useCsrfToken, useIsSearchScopeChildrenAsDefault, useCurrentPageId, useCurrentPathname,
  68. useIsSlackConfigured, useRendererConfig,
  69. useEditorConfig, useIsAllReplyShown, useIsUploadableFile, useIsUploadableImage, useIsContainerFluid, useIsNotCreatable,
  70. } from '../stores/context';
  71. import { NextPageWithLayout } from './_app.page';
  72. import {
  73. CommonProps, getNextI18NextConfig, getServerSideCommonProps, generateCustomTitle,
  74. } from './utils/commons';
  75. declare global {
  76. // eslint-disable-next-line vars-on-top, no-var
  77. var globalEmitter: EventEmitter;
  78. }
  79. const NotCreatablePage = dynamic(() => import('../components/NotCreatablePage').then(mod => mod.NotCreatablePage), { ssr: false });
  80. const ForbiddenPage = dynamic(() => import('../components/ForbiddenPage'), { ssr: false });
  81. const UnsavedAlertDialog = dynamic(() => import('../components/UnsavedAlertDialog'), { ssr: false });
  82. const PageSideContents = dynamic<PageSideContentsProps>(() => import('../components/PageSideContents').then(mod => mod.PageSideContents), { ssr: false });
  83. const GrowiSubNavigationSwitcher = dynamic(() => import('../components/Navbar/GrowiSubNavigationSwitcher'), { ssr: false });
  84. const UsersHomePageFooter = dynamic<UsersHomePageFooterProps>(() => import('../components/UsersHomePageFooter')
  85. .then(mod => mod.UsersHomePageFooter), { ssr: false });
  86. const DrawioModal = dynamic(() => import('../components/PageEditor/DrawioModal').then(mod => mod.DrawioModal), { ssr: false });
  87. const HandsontableModal = dynamic(() => import('../components/PageEditor/HandsontableModal').then(mod => mod.HandsontableModal), { ssr: false });
  88. const PageStatusAlert = dynamic(() => import('../components/PageStatusAlert').then(mod => mod.PageStatusAlert), { ssr: false });
  89. const logger = loggerFactory('growi:pages:all');
  90. const {
  91. isPermalink: _isPermalink, isUsersHomePage, isTrashPage: _isTrashPage, isCreatablePage, isTopPage,
  92. } = pagePathUtils;
  93. const { removeHeadingSlash } = pathUtils;
  94. type IPageToShowRevisionWithMeta = IDataWithMeta<IPagePopulatedToShowRevision & PageDocument, IPageInfoForEntity>;
  95. type IPageToShowRevisionWithMetaSerialized = IDataWithMeta<string, string>;
  96. superjson.registerCustom<IPageToShowRevisionWithMeta, IPageToShowRevisionWithMetaSerialized>(
  97. {
  98. isApplicable: (v): v is IPageToShowRevisionWithMeta => {
  99. return v?.data != null
  100. && v?.data.toObject != null
  101. && v?.meta != null
  102. && isIPageInfoForEntity(v.meta);
  103. },
  104. serialize: (v) => {
  105. return {
  106. data: superjson.stringify(v.data.toObject()),
  107. meta: superjson.stringify(v.meta),
  108. };
  109. },
  110. deserialize: (v) => {
  111. return {
  112. data: superjson.parse(v.data),
  113. meta: v.meta != null ? superjson.parse(v.meta) : undefined,
  114. };
  115. },
  116. },
  117. 'IPageToShowRevisionWithMetaTransformer',
  118. );
  119. const IdenticalPathPage = (): JSX.Element => {
  120. const IdenticalPathPage = dynamic(() => import('../components/IdenticalPathPage').then(mod => mod.IdenticalPathPage), { ssr: false });
  121. return <IdenticalPathPage />;
  122. };
  123. const PutbackPageModal = (): JSX.Element => {
  124. const PutbackPageModal = dynamic(() => import('../components/PutbackPageModal'), { ssr: false });
  125. return <PutbackPageModal />;
  126. };
  127. type Props = CommonProps & {
  128. currentUser: IUser,
  129. pageWithMeta: IPageToShowRevisionWithMeta | null,
  130. // pageUser?: any,
  131. redirectFrom?: string;
  132. // shareLinkId?: string;
  133. isLatestRevision?: boolean,
  134. isIdenticalPathPage?: boolean,
  135. isForbidden: boolean,
  136. isNotFound: boolean,
  137. isNotCreatable: boolean,
  138. // isAbleToDeleteCompletely: boolean,
  139. templateTagData?: string[],
  140. templateBodyData?: string,
  141. isSearchServiceConfigured: boolean,
  142. isSearchServiceReachable: boolean,
  143. isSearchScopeChildrenAsDefault: boolean,
  144. isSlackConfigured: boolean,
  145. // isMailerSetup: boolean,
  146. isAclEnabled: boolean,
  147. // hasSlackConfig: boolean,
  148. drawioUri: string | null,
  149. hackmdUri: string,
  150. noCdn: string,
  151. // highlightJsStyle: string,
  152. isAllReplyShown: boolean,
  153. isContainerFluid: boolean,
  154. editorConfig: EditorConfig,
  155. isEnabledStaleNotification: boolean,
  156. isEnabledAttachTitleHeader: boolean,
  157. // isEnabledLinebreaks: boolean,
  158. // isEnabledLinebreaksInComments: boolean,
  159. adminPreferredIndentSize: number,
  160. isIndentSizeForced: boolean,
  161. disableLinkSharing: boolean,
  162. grantData?: IPageGrantData,
  163. rendererConfig: RendererConfig,
  164. // UI
  165. userUISettings?: IUserUISettings
  166. // Sidebar
  167. sidebarConfig: ISidebarConfig,
  168. };
  169. const Page: NextPageWithLayout<Props> = (props: Props) => {
  170. // const { t } = useTranslation();
  171. const router = useRouter();
  172. const { data: currentUser } = useCurrentUser(props.currentUser ?? null);
  173. // register global EventEmitter
  174. if (isClient() && window.globalEmitter == null) {
  175. window.globalEmitter = new EventEmitter();
  176. }
  177. // commons
  178. useEditorConfig(props.editorConfig);
  179. useCsrfToken(props.csrfToken);
  180. // UserUISettings
  181. usePreferDrawerModeByUser(props.userUISettings?.preferDrawerModeByUser ?? props.sidebarConfig.isSidebarDrawerMode);
  182. usePreferDrawerModeOnEditByUser(props.userUISettings?.preferDrawerModeOnEditByUser);
  183. useSidebarCollapsed(props.userUISettings?.isSidebarCollapsed ?? props.sidebarConfig.isSidebarClosedAtDockMode);
  184. useCurrentSidebarContents(props.userUISettings?.currentSidebarContents);
  185. useCurrentProductNavWidth(props.userUISettings?.currentProductNavWidth);
  186. // page
  187. useIsLatestRevision(props.isLatestRevision);
  188. useIsContainerFluid(props.isContainerFluid);
  189. // useOwnerOfCurrentPage(props.pageUser != null ? JSON.parse(props.pageUser) : null);
  190. useIsForbidden(props.isForbidden);
  191. useIsNotFound(props.isNotFound);
  192. useIsNotCreatable(props.isNotCreatable);
  193. useRedirectFrom(props.redirectFrom ?? null);
  194. useIsSharedUser(false); // this page cann't be routed for '/share'
  195. useIsIdenticalPath(props.isIdenticalPathPage ?? false);
  196. useIsEnabledStaleNotification(props.isEnabledStaleNotification);
  197. useIsSearchPage(false);
  198. useTemplateTagData(props.templateTagData);
  199. useTemplateBodyData(props.templateBodyData);
  200. useIsEnabledAttachTitleHeader(props.isEnabledAttachTitleHeader);
  201. useIsSearchServiceConfigured(props.isSearchServiceConfigured);
  202. useIsSearchServiceReachable(props.isSearchServiceReachable);
  203. useIsSearchScopeChildrenAsDefault(props.isSearchScopeChildrenAsDefault);
  204. useIsSlackConfigured(props.isSlackConfigured);
  205. // useIsMailerSetup(props.isMailerSetup);
  206. useIsAclEnabled(props.isAclEnabled);
  207. // useHasSlackConfig(props.hasSlackConfig);
  208. useDrawioUri(props.drawioUri);
  209. useHackmdUri(props.hackmdUri);
  210. // useNoCdn(props.noCdn);
  211. useDefaultIndentSize(props.adminPreferredIndentSize);
  212. useIsIndentSizeForced(props.isIndentSizeForced);
  213. useDisableLinkSharing(props.disableLinkSharing);
  214. useRendererConfig(props.rendererConfig);
  215. // useRendererSettings(props.rendererSettingsStr != null ? JSON.parse(props.rendererSettingsStr) : undefined);
  216. // useGrowiRendererConfig(props.growiRendererConfigStr != null ? JSON.parse(props.growiRendererConfigStr) : undefined);
  217. useIsAllReplyShown(props.isAllReplyShown);
  218. useIsUploadableFile(props.editorConfig.upload.isUploadableFile);
  219. useIsUploadableImage(props.editorConfig.upload.isUploadableImage);
  220. const { pageWithMeta, userUISettings } = props;
  221. const pageId = pageWithMeta?.data._id;
  222. const pagePath = pageWithMeta?.data.path ?? (!_isPermalink(props.currentPathname) ? props.currentPathname : undefined);
  223. useCurrentPageId(pageId ?? null);
  224. useRevisionIdHackmdSynced(pageWithMeta?.data.revisionHackmdSynced);
  225. useRemoteRevisionId(pageWithMeta?.data.revision?._id);
  226. usePageIdOnHackmd(pageWithMeta?.data.pageIdOnHackmd);
  227. useHasDraftOnHackmd(pageWithMeta?.data.hasDraftOnHackmd ?? false);
  228. useCurrentPathname(props.currentPathname);
  229. useSWRxCurrentPage(pageWithMeta?.data ?? null); // store initial data
  230. useEditingMarkdown(pageWithMeta?.data.revision?.body);
  231. const { data: grantData } = useSWRxIsGrantNormalized(pageId);
  232. const { mutate: mutateSelectedGrant } = useSelectedGrant();
  233. useSetupGlobalSocket();
  234. useSetupGlobalSocketForPage(pageId);
  235. const growiLayoutFluidClass = useCurrentGrowiLayoutFluidClassName();
  236. const shouldRenderPutbackPageModal = pageWithMeta != null
  237. ? _isTrashPage(pageWithMeta.data.path)
  238. : false;
  239. // sync grant data
  240. useEffect(() => {
  241. const grantDataToApply = props.grantData ? props.grantData : grantData?.grantData.currentPageGrant;
  242. mutateSelectedGrant(grantDataToApply);
  243. }, [grantData?.grantData.currentPageGrant, mutateSelectedGrant, props.grantData]);
  244. // sync pathname by Shallow Routing https://nextjs.org/docs/routing/shallow-routing
  245. useEffect(() => {
  246. const decodedURI = decodeURI(window.location.pathname);
  247. if (isClient() && decodedURI !== props.currentPathname) {
  248. const { search, hash } = window.location;
  249. router.replace(`${props.currentPathname}${search}${hash}`, undefined, { shallow: true });
  250. }
  251. }, [props.currentPathname, router]);
  252. const isTopPagePath = isTopPage(pageWithMeta?.data.path ?? '');
  253. const title = generateCustomTitle(props, 'GROWI');
  254. const sideContents = !props.isNotFound && !props.isNotCreatable
  255. ? (
  256. <PageSideContents page={pageWithMeta?.data} />
  257. )
  258. : <></>;
  259. const footerContents = !props.isIdenticalPathPage && !props.isNotFound && pageWithMeta != null
  260. ? (
  261. <>
  262. { pagePath != null && !isTopPagePath && (
  263. <Comments pageId={pageId} pagePath={pagePath} revision={pageWithMeta.data.revision} />
  264. ) }
  265. { isUsersHomePage(pageWithMeta.data.path) && (
  266. <UsersHomePageFooter creatorId={pageWithMeta.data.creator._id}/>
  267. ) }
  268. <PageContentFooter page={pageWithMeta.data} />
  269. </>
  270. )
  271. : <></>;
  272. return (
  273. <>
  274. <Head>
  275. <title>{title}</title>
  276. </Head>
  277. <div className={`dynamic-layout-root ${growiLayoutFluidClass} h-100 d-flex flex-column justify-content-between`}>
  278. <header className="py-0 position-relative">
  279. <div id="grw-subnav-container">
  280. <GrowiContextualSubNavigation currentPage={pageWithMeta?.data} isLinkSharingDisabled={props.disableLinkSharing} />
  281. </div>
  282. </header>
  283. <div className="d-edit-none">
  284. <GrowiSubNavigationSwitcher />
  285. </div>
  286. <div id="grw-subnav-sticky-trigger" className="sticky-top"></div>
  287. <div id="grw-fav-sticky-trigger" className="sticky-top"></div>
  288. <MainPane
  289. sideContents={sideContents}
  290. footerContents={footerContents}
  291. >
  292. <PageAlerts />
  293. { props.isIdenticalPathPage && <IdenticalPathPage />}
  294. { !props.isIdenticalPathPage && (
  295. <>
  296. { props.isForbidden && <ForbiddenPage /> }
  297. { props.isNotCreatable && <NotCreatablePage />}
  298. { !props.isForbidden && !props.isNotCreatable && <DisplaySwitcher />}
  299. </>
  300. ) }
  301. <PageStatusAlert />
  302. </MainPane>
  303. {shouldRenderPutbackPageModal && <PutbackPageModal />}
  304. </div>
  305. </>
  306. );
  307. };
  308. Page.getLayout = function getLayout(page) {
  309. return (
  310. <>
  311. <DrawioViewerScript />
  312. <BasicLayoutWithEditorMode>
  313. {page}
  314. </BasicLayoutWithEditorMode>
  315. <UnsavedAlertDialog />
  316. <DescendantsPageListModal />
  317. <DrawioModal />
  318. <HandsontableModal />
  319. </>
  320. );
  321. };
  322. function getPageIdFromPathname(currentPathname: string): string | null {
  323. return _isPermalink(currentPathname) ? removeHeadingSlash(currentPathname) : null;
  324. }
  325. class MultiplePagesHitsError extends ExtensibleCustomError {
  326. pagePath: string;
  327. constructor(pagePath: string) {
  328. super(`MultiplePagesHitsError occured by '${pagePath}'`);
  329. this.pagePath = pagePath;
  330. }
  331. }
  332. // apply parent page grant fot creating page
  333. async function applyGrantToPage(props: Props, ancestor: any) {
  334. await ancestor.populate('grantedGroup');
  335. const grant = {
  336. grant: ancestor.grant,
  337. };
  338. const grantedGroup = ancestor.grantedGroup ? {
  339. grantedGroup: {
  340. id: ancestor.grantedGroup.id,
  341. name: ancestor.grantedGroup.name,
  342. },
  343. } : {};
  344. props.grantData = Object.assign(grant, grantedGroup);
  345. }
  346. async function injectPageData(context: GetServerSidePropsContext, props: Props): Promise<void> {
  347. const { model: mongooseModel } = await import('mongoose');
  348. const req: CrowiRequest = context.req as CrowiRequest;
  349. const { crowi } = req;
  350. const { revisionId } = req.query;
  351. const Page = crowi.model('Page') as PageModel;
  352. const PageRedirect = mongooseModel('PageRedirect') as PageRedirectModel;
  353. const { pageService } = crowi;
  354. let currentPathname = props.currentPathname;
  355. const pageId = getPageIdFromPathname(currentPathname);
  356. const isPermalink = _isPermalink(currentPathname);
  357. const { user } = req;
  358. if (!isPermalink) {
  359. // check redirects
  360. const chains = await PageRedirect.retrievePageRedirectEndpoints(currentPathname);
  361. if (chains != null) {
  362. // overwrite currentPathname
  363. currentPathname = chains.end.toPath;
  364. props.currentPathname = currentPathname;
  365. // set redirectFrom
  366. props.redirectFrom = chains.start.fromPath;
  367. }
  368. // check whether the specified page path hits to multiple pages
  369. const count = await Page.countByPathAndViewer(currentPathname, user, null, true);
  370. if (count > 1) {
  371. throw new MultiplePagesHitsError(currentPathname);
  372. }
  373. }
  374. const pageWithMeta: IPageToShowRevisionWithMeta | null = await pageService.findPageAndMetaDataByViewer(pageId, currentPathname, user, true); // includeEmpty = true, isSharedPage = false
  375. const page = pageWithMeta?.data as unknown as PageDocument;
  376. // add user to seen users
  377. if (page != null && user != null) {
  378. await page.seen(user);
  379. }
  380. // populate & check if the revision is latest
  381. if (page != null) {
  382. page.initLatestRevisionField(revisionId);
  383. await page.populateDataToShowRevision();
  384. props.isLatestRevision = page.isLatestRevision();
  385. }
  386. if (page == null && user != null) {
  387. const templateData = await Page.findTemplate(props.currentPathname);
  388. if (templateData != null) {
  389. props.templateTagData = templateData.templateTags as string[];
  390. props.templateBodyData = templateData.templateBody as string;
  391. // take over pagrent page grant
  392. const ancestor = await Page.findAncestorByPathAndViewer(currentPathname, user);
  393. if (ancestor != null) {
  394. await applyGrantToPage(props, ancestor);
  395. }
  396. }
  397. }
  398. props.pageWithMeta = pageWithMeta;
  399. }
  400. async function injectUserUISettings(context: GetServerSidePropsContext, props: Props): Promise<void> {
  401. const { model: mongooseModel } = await import('mongoose');
  402. const req = context.req as CrowiRequest<IUserHasId & any>;
  403. const { user } = req;
  404. const UserUISettings = mongooseModel('UserUISettings') as UserUISettingsModel;
  405. const userUISettings = user == null ? null : await UserUISettings.findOne({ user: user._id }).exec();
  406. if (userUISettings != null) {
  407. props.userUISettings = userUISettings.toObject();
  408. }
  409. }
  410. async function injectRoutingInformation(context: GetServerSidePropsContext, props: Props): Promise<void> {
  411. const req: CrowiRequest = context.req as CrowiRequest;
  412. const { crowi } = req;
  413. const Page = crowi.model('Page') as PageModel;
  414. const { currentPathname } = props;
  415. const pageId = getPageIdFromPathname(currentPathname);
  416. const isPermalink = _isPermalink(currentPathname);
  417. const page = props.pageWithMeta?.data;
  418. if (props.isIdenticalPathPage) {
  419. props.isNotCreatable = true;
  420. }
  421. else if (page == null) {
  422. props.isNotFound = true;
  423. props.isNotCreatable = !isCreatablePage(currentPathname);
  424. // check the page is forbidden or just does not exist.
  425. const count = isPermalink ? await Page.count({ _id: pageId }) : await Page.count({ path: currentPathname });
  426. props.isForbidden = count > 0;
  427. }
  428. else {
  429. props.isNotFound = page.isEmpty;
  430. props.isNotCreatable = false;
  431. // /62a88db47fed8b2d94f30000 ==> /path/to/page
  432. if (isPermalink && page.isEmpty) {
  433. props.currentPathname = page.path;
  434. }
  435. // /path/to/page ==> /62a88db47fed8b2d94f30000
  436. if (!isPermalink && !page.isEmpty) {
  437. const isToppage = pagePathUtils.isTopPage(props.currentPathname);
  438. if (!isToppage) {
  439. props.currentPathname = `/${page._id}`;
  440. }
  441. }
  442. }
  443. }
  444. // async function injectPageUserInformation(context: GetServerSidePropsContext, props: Props): Promise<void> {
  445. // const req: CrowiRequest = context.req as CrowiRequest;
  446. // const { crowi } = req;
  447. // const UserModel = crowi.model('User');
  448. // if (isUserPage(props.currentPagePath)) {
  449. // const user = await UserModel.findUserByUsername(UserModel.getUsernameByPath(props.currentPagePath));
  450. // if (user != null) {
  451. // props.pageUser = JSON.stringify(user.toObject());
  452. // }
  453. // }
  454. // }
  455. function injectServerConfigurations(context: GetServerSidePropsContext, props: Props): void {
  456. const req: CrowiRequest = context.req as CrowiRequest;
  457. const { crowi } = req;
  458. const {
  459. appService, searchService, configManager, aclService, slackNotificationService, mailService,
  460. } = crowi;
  461. props.isSearchServiceConfigured = searchService.isConfigured;
  462. props.isSearchServiceReachable = searchService.isReachable;
  463. props.isSearchScopeChildrenAsDefault = configManager.getConfig('crowi', 'customize:isSearchScopeChildrenAsDefault');
  464. props.isSlackConfigured = crowi.slackIntegrationService.isSlackConfigured;
  465. // props.isMailerSetup = mailService.isMailerSetup;
  466. props.isAclEnabled = aclService.isAclEnabled();
  467. // props.hasSlackConfig = slackNotificationService.hasSlackConfig();
  468. props.drawioUri = configManager.getConfig('crowi', 'app:drawioUri');
  469. props.hackmdUri = configManager.getConfig('crowi', 'app:hackmdUri');
  470. props.noCdn = configManager.getConfig('crowi', 'app:noCdn');
  471. // props.highlightJsStyle = configManager.getConfig('crowi', 'customize:highlightJsStyle');
  472. props.isAllReplyShown = configManager.getConfig('crowi', 'customize:isAllReplyShown');
  473. props.isContainerFluid = configManager.getConfig('crowi', 'customize:isContainerFluid');
  474. props.isEnabledStaleNotification = configManager.getConfig('crowi', 'customize:isEnabledStaleNotification');
  475. props.disableLinkSharing = configManager.getConfig('crowi', 'security:disableLinkSharing');
  476. props.editorConfig = {
  477. upload: {
  478. isUploadableFile: crowi.fileUploadService.getFileUploadEnabled(),
  479. isUploadableImage: crowi.fileUploadService.getIsUploadable(),
  480. },
  481. };
  482. props.adminPreferredIndentSize = configManager.getConfig('markdown', 'markdown:adminPreferredIndentSize');
  483. props.isIndentSizeForced = configManager.getConfig('markdown', 'markdown:isIndentSizeForced');
  484. props.isEnabledAttachTitleHeader = configManager.getConfig('crowi', 'customize:isEnabledAttachTitleHeader');
  485. props.rendererConfig = {
  486. isEnabledLinebreaks: configManager.getConfig('markdown', 'markdown:isEnabledLinebreaks'),
  487. isEnabledLinebreaksInComments: configManager.getConfig('markdown', 'markdown:isEnabledLinebreaksInComments'),
  488. adminPreferredIndentSize: configManager.getConfig('markdown', 'markdown:adminPreferredIndentSize'),
  489. isIndentSizeForced: configManager.getConfig('markdown', 'markdown:isIndentSizeForced'),
  490. plantumlUri: process.env.PLANTUML_URI ?? null,
  491. blockdiagUri: process.env.BLOCKDIAG_URI ?? null,
  492. // XSS Options
  493. attrWhiteList: crowi.xssService.getAttrWhiteList(),
  494. tagWhiteList: crowi.xssService.getTagWhiteList(),
  495. highlightJsStyleBorder: crowi.configManager.getConfig('crowi', 'customize:highlightJsStyleBorder'),
  496. // XSS: rehype-sanitize options
  497. isEnabledXssPrevention: configManager.getConfig('markdown', 'markdown:rehypeSanitize:isEnabledPrevention'),
  498. };
  499. props.sidebarConfig = {
  500. isSidebarDrawerMode: configManager.getConfig('crowi', 'customize:isSidebarDrawerMode'),
  501. isSidebarClosedAtDockMode: configManager.getConfig('crowi', 'customize:isSidebarClosedAtDockMode'),
  502. };
  503. }
  504. /**
  505. * for Server Side Translations
  506. * @param context
  507. * @param props
  508. * @param namespacesRequired
  509. */
  510. async function injectNextI18NextConfigurations(context: GetServerSidePropsContext, props: Props, namespacesRequired?: string[] | undefined): Promise<void> {
  511. const nextI18NextConfig = await getNextI18NextConfig(serverSideTranslations, context, namespacesRequired);
  512. props._nextI18Next = nextI18NextConfig._nextI18Next;
  513. }
  514. export const getServerSideProps: GetServerSideProps = async(context: GetServerSidePropsContext) => {
  515. const req = context.req as CrowiRequest<IUserHasId & any>;
  516. const { user } = req;
  517. const result = await getServerSideCommonProps(context);
  518. // check for presence
  519. // see: https://github.com/vercel/next.js/issues/19271#issuecomment-730006862
  520. if (!('props' in result)) {
  521. throw new Error('invalid getSSP result');
  522. }
  523. const props: Props = result.props as Props;
  524. if (props.redirectDestination != null) {
  525. return {
  526. redirect: {
  527. permanent: false,
  528. destination: props.redirectDestination,
  529. },
  530. };
  531. }
  532. if (user != null) {
  533. props.currentUser = user.toObject();
  534. }
  535. try {
  536. await injectPageData(context, props);
  537. }
  538. catch (err) {
  539. if (err instanceof MultiplePagesHitsError) {
  540. props.isIdenticalPathPage = true;
  541. }
  542. else {
  543. throw err;
  544. }
  545. }
  546. await injectUserUISettings(context, props);
  547. await injectRoutingInformation(context, props);
  548. injectServerConfigurations(context, props);
  549. await injectNextI18NextConfigurations(context, props, ['translation']);
  550. return {
  551. props,
  552. };
  553. };
  554. export default Page;